//
//  XDShakeSearchViewController.m
//  Le way walkers
//
//  Created by POP-mac on 15/5/23.
//  Copyright (c) 2015年 LTXZ. All rights reserved.
//

#import "XDShakeSearchViewController.h"
#import "XDShakeViewController.h"
#import "XDShakeSearchCollectionViewCell.h"
#import "XDShakeSearch.h"
#import "NNetworkHandle.h"
#import "XDDetailsViewController.h"
#import "MJRefresh.h"

@interface XDShakeSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) NSInteger num_message;
@end

@implementation XDShakeSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = [NSString stringWithFormat:@"搜索'%@'", self.search_text];
    self.array = [NSMutableArray array];
    [self getDate];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)create
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, 110);
    flowLayout.minimumInteritemSpacing = 10;
    self.collectionView = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout] autorelease];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:248 / 255.0 blue:240 / 255.0 alpha:1];
    [self.collectionView addFooterWithCallback:^{
        //
        [self getDate];
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[XDShakeSearchCollectionViewCell class] forCellWithReuseIdentifier:@"searchCell"];
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XDDetailsViewController *xd = [[[XDDetailsViewController alloc] init] autorelease];
    xd.ids = [self.array[indexPath.row] ids];
    xd.name = [self.array[indexPath.row] name];
    [self.navigationController pushViewController:xd animated:YES];
}

- (void)getDate
{
    if (self.num >= 1) {
        self.num_message = self.num * 20 + 5;
    }
    NSString *utf = self.search_text;
    NSLog(@"******%@", utf);
    utf = [utf stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~<>$€^•'.!/@#$%^&*()_+'\""];
    utf = [[utf componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
    NSLog(@"------%@", utf);
    utf = [utf stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"******%@", utf);
    [NNetworkHandle getDataWithUrl:[NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=%ld&count=20", utf, self.num_message] Cookie:@"sessionid=256c546b7892e31bd78f3cd9d9c200bd; bt_devid=a_8f22e38eeda805d03f5ceacc53bdea86841d9a13218d2015edc1a3c46e41fa62; refer_android_source=105" completion:^(id result) {
        NSLog(@"*****%@", result);
        NSArray *arr = [result objectForKey:@"trips"];
        if (arr.count <= 1) {
            NSLog(@"kong");
            [self kong];
            return;
        }
        for (NSDictionary *dic in arr) {
            XDShakeSearch *xd = [[[XDShakeSearch alloc] init] autorelease];
            [xd setValuesForKeysWithDictionary:dic];
            [self.array addObject:xd];
        }
        NSLog(@"%@", [[self.array objectAtIndex:0] name]);
        if (self.num >= 1) {
            [self.collectionView reloadData];
        }
        else
        {
            [self create];
        }
        self.num = self.num + 1;
        [self.collectionView footerEndRefreshing];
    }];
}

- (void)kong
{
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有搜到相关信息,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [av show];
    [av release];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XDShakeSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchCell" forIndexPath:indexPath];
    XDShakeSearch *xd = self.array[indexPath.row];
    cell.shakeSearch = xd;
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.array.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
